package com.lxp.tksys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxp.tksys.dto.DishDto;
import com.lxp.tksys.entity.Dish;
import com.lxp.tksys.entity.DishFlavor;
import com.lxp.tksys.entity.Employee;
import com.lxp.tksys.mapper.DishMapper;
import com.lxp.tksys.mapper.EmployMapper;
import com.lxp.tksys.service.DishFlavorService;
import com.lxp.tksys.service.DishService;
import com.lxp.tksys.service.EmployService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {  // 新增时加入口味信息
        this.save(dishDto);

        Long dishId = dishDto.getId();   //dishDto的id作为flavors的dishid，不是一个东西,一个是id一个是dishid所以才要设置一遍
        //获取id和口味集合，再将dishid set进口味对象中
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors=flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        //批量保存
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {          //返回带有口味信息的对象
        Dish dish = this.getById(id);   //获取id
        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish,dishDto);  //赋值

        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);  //通过dishid找到口味

        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {     // 更新菜品、口味

        this.updateById(dishDto);

        //先根据dishid清理口味，在添加
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lambdaQueryWrapper);

        List<DishFlavor> flavors = dishDto.getFlavors();   //获取口味再set dishid

        flavors=flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);


    }
}
